/*
  * @brief:    使用消息队列实现简单的裸机任务调度            
  * @author:   guangjieMVP
  * @date:     2020-12-25
  * @version:  v1.0.0
  * @  copyright(c) 2020: OptoMedic Technologies Co.,Ltd. All rights reserved
*/

#include "msgqueue-drv.h"
#include "stdio.h"

/**
  * @brief:        判斷環形隊列是否空
  * @param[in]:     None
  * @retval[out]:   None
  * @author:       AresXu
  * @version:      v1.0.0
*/
static uint8_t IsMsgQueueEmpty(stMsgQueue *mqHead)
{
    if(mqHead->in == mqHead->out)
    {
        return 1;
    }
    return 0;
}

/**
  * @brief:         判斷環形隊列是否满
  * @param[in]:     None
  * @retval[out]:   None
  * @note:            
  * @author:       AresXu
  * @version:      v1.0.0
*/
static uint8_t IsMsgQueueFull(stMsgQueue *mqHead)
{
    if ( ( (mqHead->in+1) % MSG_QUEUE_SIZE) == mqHead->out)
    {
        return 1;
    }
	
    return 0;
}

uint8_t MQ_PublishMsg(stMsgQueue *mqHead, MsgType msg)
{
    if ( IsMsgQueueFull (mqHead) == 1 )           //队列满不能写入消息
    {
        return 0;
    }

    mqHead->buf[mqHead->in] = msg;
	// msg->handler(NULL);
    mqHead->in = (++mqHead->in) % MSG_QUEUE_SIZE;    //防止越界
	
	return 1;
}


uint8_t MQ_GetMsg(stMsgQueue *mqHead, MsgType *msg)
{
    if ( IsMsgQueueEmpty(mqHead) )
    {
        return 0;
    }

    *msg = mqHead->buf[mqHead->out];
    mqHead->out = (++mqHead->out) % MSG_QUEUE_SIZE;    //防止越界
    return 1;
} 


// //主函数循环调用
void MsgQueTask_Handle(stMsgQueue *mqHead, stMsgHandle *msghs, uint8_t num)
{
	MsgType msg;
    uint8_t i; 

	while (MQ_GetMsg(mqHead, &msg))
	{
		for (i = 0; i < num; i++)
        {
            if (msghs[i].msg == msg)
            {
                if (msghs[i].msg_handler)
                    msghs[i].msg_handler();
            }
        }
	}
}







